# -*- coding: utf-8 -*-
import json
import os

from util.selenium.webdriver.common.by import By
from util.selenium.common.exceptions import TimeoutException

from base.BaseMethod import BM
# 导入 超级鹰 账号信息
from settings import soft_id, username, password
from util.DataQuery.DbTools import DbTools
from util.DataQuery.hzflowOperation import hzflowOperation
from util.chaojiying import Chaojiying_Client
from util.g import g
from util.GetValidateCodeImg import GetImg


class LoginPage():
    # 用户登录入口
    login_enter_loc = (By.CSS_SELECTOR, "div#menu-wrap>div:nth-of-type(2) a:nth-of-type(1)")

    login_box_loc = (By.XPATH, "//iframe[contains(@id,'layui-layer-iframe')]")
    # 法人登录
    login_tab_loc = (By.CSS_SELECTOR, "div.login-tabs span:nth-of-type(2)")

    # 自然人登录
    person_tab_loc = (By.CSS_SELECTOR, "div.login-tabs span:nth-of-type(1)")

    # username_input_loc = (By.CSS_SELECTOR, 'input#entUsername')
    username_input_loc = (By.CSS_SELECTOR, 'input#loginName')
    # password_input_loc = (By.CSS_SELECTOR, 'input#entPassword')
    password_input_loc = (By.CSS_SELECTOR, 'input#password')
    # validate_code_img_loc = (By.CSS_SELECTOR, ".iconBox .yanzhengma img")
    validate_code_img_loc = (By.CSS_SELECTOR, "#code2")
    validate_code_input_loc = (By.CSS_SELECTOR, 'input#validateCode')

    # 网页中被去除
    # label_error_loc = (By.CSS_SELECTOR, 'label.error')

    # 登录异常提示框及关闭按钮
    tip_loc = (By.CSS_SELECTOR, ".layui-layer.layui-layer-dialog.layui-layer-border.layui-layer-msg.layui-layer-hui"
                                " .layui-layer-content")
    tip_btn_loc = (By.CSS_SELECTOR, ".layui-layer.layui-layer-dialog.layui-layer-border.layui-layer-msg.layui-layer-hui"
                                    " .layui-layer-btn0")

    ad_loc = (By.CSS_SELECTOR, 'div#float_ad')
    close_ad_js = f"document.querySelector(a#close_float_ad).click()"

    # login_btn_loc = (By.CSS_SELECTOR, 'button#subtn_ent')
    login_btn_loc = (By.CSS_SELECTOR, 'input#login-submit')
    cjy = Chaojiying_Client(username=username, password=password, soft_id=soft_id)

    result = ""

    def __init__(self, driver):
        self.driver = driver

    def input_username(self, username):
        BM.input(driver=self.driver, ele_loc=self.username_input_loc, keys=username)

    def input_password(self, password):
        BM.input(driver=self.driver, ele_loc=self.password_input_loc, keys=password)

    # TODO 这里需要进行登录优化
    def check_error(self):
        # labels = None
        try:
            BM.driver_wait(driver=self.driver, ele_loc=self.login_btn_loc, time=5, is_not=True)
        except TimeoutException as err:
            error:bool = BM.wait_ele_exist(driver=self.driver, ele_loc=self.tip_loc)
            if error:
                tip_divs = self.driver.find_elements(*self.tip_loc)
                error_str = ','.join([i.text for i in tip_divs])
                BM.click(driver=self.driver, ele_loc=self.tip_btn_loc, wait="driver_wait")
                if not tip_divs:
                    return False
                if u"自然人登录" in error_str:
                    g.logger.error("登录方式错误-应为自然人登陆")
                    return "login"
                if u'验证码' in error_str:
                    g.logger.error('验证码错误'.center(90, '-'))
                    if not g.is_test:
                        self.cjy.ReportError(im_id=self.result_dict.get("pic_id"))
                    return "yzm"
                if u"登录名" in error_str or u"密码" in error_str:
                    g.logger.error("用户名或密码错误: 网站提示 --- {}".format(error_str))
                    # TODO 更新 线上 状态表 中的状态 ul_status -> -1
                    map = {"ul_status": -1, "c_idstatus": 1}
                    DbTools.update_entrestatus_fields(map, co_id=g.co_id, year=g.year)
                    hzflowOperation.update_host_process(obj=hzflowOperation.get_log(g.co_id, g.year), mark_info="")
                    hzflowOperation.update_field(obj=hzflowOperation.get_logs(g.co_id, g.year), field_name="login_status",
                                                 field_value=-1)
                    self.driver.quit()
                    return True

        # else:
        return False

    def close_ad(self):
        ad = BM.isElementExist(element=self.ad_loc, driver=self.driver)
        if ad:
            self.driver.execute(self.close_ad_js)

    def input_validate_code(self):
        validate_code_value = None
        # 声明图片路径
        img_path:str
        if not g.is_test:
            get_vc = GetImg(self.driver)
            img_path = get_vc.get_img(ele_loc=self.validate_code_img_loc)
            # result_dict = image_decode(filename=img_path)
            result_dict = self.cjy.PostPicPath(img_path=img_path)
            self.result_dict = result_dict
            g.logger.info("验证码识别：{}".format(json.dumps(result_dict)))
            validate_code_value = result_dict.get("pic_str")
            # TODO {'err_no': 0, 'err_str': 'OK', 'pic_id': '9107416044412900024', 'pic_str': 'xdg7', 'md5': '8d7ad2cc81e2c673735650bc06c71b24'}

            # validate_code_value = result_dict.get('result')
            # cid = result_dict.get('cid')
            # if cid  == -3003:
            #     raise TimeoutError('验证码识别超时')

        else:
            get_vc = GetImg(self.driver)
            img_path = get_vc.get_img(ele_loc=self.validate_code_img_loc)
            validate_code_value = input("（测试）请输入验证码：")

        BM.input(driver=self.driver, ele_loc=self.validate_code_input_loc, keys=validate_code_value)
        return img_path, validate_code_value

    def click_locin_btn(self):
        # self.driver.find_element(*self.login_btn_loc).click()
        BM.click(driver=self.driver, ele_loc=self.login_btn_loc)

    def click_login_tab(self, ele_loc):
        login_tab = BM.get_ele(driver=self.driver, ele_loc=ele_loc)
        if "activ" not in login_tab.get_attribute("class"):
            BM.click(driver=self.driver, ele_loc=ele_loc)

    def login(self, c_username='91320411MA20201Y6Q', c_userpwd='Hz123456'):

        time = 0
        BM.click(driver=self.driver, ele_loc=self.login_enter_loc)
        # BM.switch_to_frame(driver=self.driver, ele_loc=self.login_box_loc)
        self.driver.switch_to.frame(self.driver.find_element_by_xpath("//iframe[contains(@id,'layui-layer-iframe')]"))
        self.click_login_tab(ele_loc=self.login_tab_loc)
        g.login = 1
        BM.click(driver=self.driver, ele_loc=(By.XPATH, "//img[@id='code2']"))
        # print("login_page:       ", self.driver.get_cookies())
        while True:
            if not BM.isElementExist(element=self.username_input_loc, driver=self.driver):
                BM.click(driver=self.driver, ele_loc=self.login_enter_loc)
            if self.result == "login":
                g.login = 2
                print("点击自然人登录")
                self.click_login_tab(ele_loc=self.person_tab_loc)
            else:
                g.login = 1
                self.click_login_tab(ele_loc=self.login_tab_loc)
            self.input_username(c_username)

            self.input_password(c_userpwd)
            img_path, validate_code_value = self.input_validate_code()
            self.click_locin_btn()
            # # # 这里检测网页 登录按钮什么时候不存在， 使用 WebDriverWait ，如果显式等待报错， 则视为登录错误， 然后执行 check_error 函数， 如果 check_error
            # 错误捕获。
            result = self.check_error()
            self.result = result
            if not result:
                # 当返回 False 时 登录成功将图片名称改为验证码
                (filepath, tempfilename) = os.path.split(img_path)
                (filename, extension) = os.path.splitext(tempfilename)
                try:
                    os.rename(img_path, filepath + "\\" + validate_code_value + extension)
                except Exception as err:
                    g.logger.error("验证码文件改名异常:", err)
                    pass

            g.logger.info("login check completed.")
            if type(result) == bool:
                if not result:
                    self.driver.switch_to.parent_frame()
                return result
            elif (result != "yzm" and result != "login") or time >= 5:
                hzflowOperation.update_host_process(obj=hzflowOperation.get_log(g.co_id, g.year), mark_info="")
                self.driver.quit()
                return True
            else:
                time += 1

# if __name__ == '__main__':
#
#     lp = LoginPage()
